<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card>
      <!-- 用户搜索区 -->
      <el-row :gutter="20">
        <el-col :span="9">
          <!-- 搜索与添加区域 -->
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区   border表格实线 stripe隔行变色-->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <!-- 状态显示要用到插槽  -->
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="190px">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteDialog(scope.row.id)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagensize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="dialogVisibleClose"
    >
      <!-- dilog  表单 -->
      <el-form
        ref="addfromRef"
        :model="addfrom"
        :rules="addfromRules"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addfrom.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addfrom.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addfrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addfrom.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialog_true">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->

    <el-dialog
      title="修改用户对话框"
      :visible.sync="editdialogVisible"
      width="50%"
      @click="editdialogClose"
    >
      <el-form
        ref="editfromRef"
        :model="editform"
        :rules="editformRules"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editform.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editform.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editform.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="edit_dialog_true">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="提示" :visible.sync="SetRoleDialogVisible" width="50%" @close = editDiologClose
    >
      <div>
        <p>当前的用户：{{ userInof.username }}</p>
        <p>当前的角色：{{ userInof.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >

            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="SetRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveaRoleInfo()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script type="text/javascript">
export default {
  data() {
    // 验证邮箱和手机号的规则
    var checkEmail = (rule, value, cb) => {
      const regEmail =
        /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };

    var checkMobile = (rule, value, cb) => {
      // /^[1][3,4,5,7,8][0-9]{9}$/;
      const regMobile = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };

    return {
      // 用户列表参数对象
      queryInfo: {
        query: "",
        // 当前页码数
        pagenum: 1,
        // 每页显示多少条数据
        pagesize: 2,
      },
      // 用户列表数据
      userList: [],
      total: 0,
      // 对话框
      dialogVisible: false,
      editdialogVisible: false,
      // 设置控制角色对话框的
      SetRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userInof: {},
      // 添加用户的表单数据
      addfrom: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 查询到的用户信息对象
      editform: {},
      // 角色数据列表
      roleList: [],
      // 已选中的角色id值
      selectRoleId: [],
      // 添加表单的验证规模对象
      addfromRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输密码", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输邮箱", trigger: "blur" },
          {
            validator: checkEmail,
            // message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输手机号", trigger: "blur" },
          {
            validator: checkMobile,
            message: "长度在 11 个字符",
            trigger: "blur",
          },
        ],
      },
      // 修改表单验证规则
      editformRules: {
        email: [
          { required: true, message: "请输邮箱", trigger: "blur" },
          {
            validator: checkEmail,
            // message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输手机号", trigger: "blur" },
          {
            validator: checkMobile,
            message: "长度在 11 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("获取管理员列表失败");
      this.userList = res.data.users;
      this.total = res.data.total;
      console.log("测试拿到数据没有userList", this.userList);
    },
    // 获取监听最新的页面  下拉点击页面
    handleSizeChange(newSize) {
      console.log(`每页 ${newSize} 条`);
      this.queryInfo.pagesize = newSize;
      // 需要从新请求改变后（每页显示的数据已经改变）  的新数据
      this.getUserList();
    },
    // 监听单个  点击单个页码  事件
    handleCurrentChange(newPage) {
      console.log(`当前页: ${newPage}`);
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    // 监听swicth开关
    async userStateChange(swich_info) {
      console.log(swich_info);
      const { data: res } = await this.$http.put(
        `users/${swich_info.id}/state/${swich_info.mg_state}`
      );
      console.log("修改状态后返回状态", res);
      if (res.meta.status !== 200) {
        swich_info.mg_state = !swich_info.mg_state;
        return this.$message.error("更改失败了", res.meta.msg);
      }
      this.$message.success("更新成功了");
    },
    //对话框关闭
    dialogVisibleClose() {
      this.$refs.addfromRef.resetFields();
    },
    // 确定前验证
    dialog_true() {
      this.$refs.addfromRef.validate(async (valid) => {
        console.log(valid);
        // 不正确返回  正确发送请求
        if (!valid) return;
        // 发送请求
        console.log("发送请求");
        const { data: res } = await this.$http.post("users", this.addfrom);
        if (res.meta.status != 200) {
          this.$message.error("添加用户失败");
          console.log("请求失败", res);
        }
        this.$message.success("添加用户成功");
        // 隐藏对话框 刷新列表
        this.dialogVisible = false;
        this.getUserList();
      });
    },
    // 展示编辑用户对话框
    async showEditDialog(id) {
      this.editdialogVisible = true;
      console.log("根据id查找的", id);
      const { data: res } = await this.$http.get("users/" + id);
      console.log(res);
      if (res.meta.status != 200) {
        this.$message.error("查询用户失败");
        // console.log("请求失败", res);
      }
      // this.$message.success("查询用户成功");
      this.editform = res.data;
      console.log(this.editform);
      this.editdialogVisible = true;
    },
    // 对话框关闭事件 重置修改rules状态 ———— 不是点击
    editdialogClose() {
      this.$refs.editfromRef.resetFields();
    },
    // 确定提交  预验证后 发送请求
    edit_dialog_true(id) {
      this.$refs.editfromRef.validate(async (valid) => {
        console.log(valid);
        // 不正确返回  正确发送请求
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "users/" + this.editform.id,
          { email: this.editform.email, mobile: this.editform.mobile }
        );
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error("跟新失败");
        }
        // 关闭对话框   刷新数据类表   提示成功
        this.editdialogVisible = false;
        this.getUserList();
        this.$message.success("跟新成功啦");
      });
    },
    // 根据id删除用户那栏
    async deleteDialog(id) {
      const res = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => error);
      // .catch(() => {
      //   this.$message({
      //     type: "info",
      //     message: "已取消删除",
      //   });
      // });
      console.log(res);
      if (res !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: ress } = await this.$http.delete("users/" + id);
      console.log(ress);
      if (ress.meta.status !== 200) {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      this.getUserList();
    },

    // 展示分配角色对话框
    async setRole(userinfo) {
      this.userInof = userinfo;
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.$message.success("成功");
      // 拿到角色数据列表
      this.roleList = res.data;
      console.log(this.roleList);
      // 展示所有角色前先获取数据列表
      this.SetRoleDialogVisible = true;
    },
    // 点击确定 分配角色
    async saveaRoleInfo() {
      // 先要判断一下用户有没有选择
      if (!this.selectRoleId) {
        return this.$message.error("您还没选择分配的角色哦");
      }

      const { data: res } = await this.$http.put(
        `users/${this.userInof.id}/role`,
        { rid: this.selectRoleId }
      );
      console.log("打印res",res);
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.$message.success("更新角色 成功");
      // 拿到角色数据列表
      this.getUserList();
      this.SetRoleDialogVisible = false;
    },
    // 监听关闭对话框  选中id 分配用户信息  都清空  以防下次点开还存在信息
    editDiologClose(){
      this.selectRoleId = ''
      this.userInof = {}
    }
  },
};
</script>

<style lang= "less" scoped>
</style>